﻿using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.User;
using Provenance.Read.Api.Application.Command.User;
using Provenance.Read.Api.Dto.User;

namespace Provenance.Read.Api.Application.CommandHandler.User
{
    public class GetPermissionListCommandHandler : IRequestHandler<GetPermissionListCommand, ApiResult<PagingResult<IList<GetPermissionListResponseDTO>>>>
    {
        private readonly IPermissionRepository _permissionRepository;
        private readonly ILogger<GetPermissionListCommandHandler> _logger;
        private readonly IMapper _mapper;
        public GetPermissionListCommandHandler(IPermissionRepository permissionRepository, ILogger<GetPermissionListCommandHandler> logger, IMapper mapper)
        {
            _permissionRepository = permissionRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult<PagingResult<IList<GetPermissionListResponseDTO>>>> Handle(GetPermissionListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var permission = await _permissionRepository.GetAllAsync(x => !x.IsDeleted);
                //左外连接，获取父级权限名
                var list = (from p in permission
                            join parent in permission on p.ParentId equals parent.PermissionId
                            into temp //join..into 把join结果放入temp
                            from t in temp.DefaultIfEmpty()
                            select new GetPermissionListResponseDTO()
                            {
                                PermissionId = p.PermissionId,
                                PermissionName = p.PermissionName,
                                ParentId = p.ParentId,
                                ParentName = t?.PermissionName ?? "",
                                Path = p.Path,
                                Name=p.Name,
                                Component=p.Component
                            }).ToList();
                var result = list.OrderBy(x => x.PermissionId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                var pagingResult = new PagingResult<IList<GetPermissionListResponseDTO>>()
                {
                    TotalCount = list.Count(),
                    TotalPage = (int)Math.Ceiling(list.Count() * 1.0 / request.PageSize),
                    Data = result
                };
                return ApiResult<PagingResult<IList<GetPermissionListResponseDTO>>>.Success(pagingResult);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error in GetPermissionListCommandHandler.Handle: " + ex.Message);
                return ApiResult<PagingResult<IList<GetPermissionListResponseDTO>>>.Failure(ex.Message);
            }
        }
    }
}
